
import axios from 'axios'
import {getToken, removeToken} from './myCookie.js'
import errorCode from './errorCode.js'
import {tansParams} from './myTools.js'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const baseURL = 'http://localhost:8080';

// 响应拦截器
	function responsePass(res) {
		// 未设置状态码则默认成功状态
		const code = res.data.code || 200;
		// 获取错误信息
		const msg = errorCode[code] || res.data.msg || errorCode['default']
		// // 二进制数据则直接返回
		// if(res.request.responseType ===  'blob' || res.request.responseType ===  'arraybuffer'){
		//   return res.data
		// }
		if (code === 401) {
		  uni.showToast({
			icon: 'none',
			title: '登录已过期，请重新登录'
		  });
		  removeToken();
		  uni.reLaunch({
			url: "/pages/login/login"
		  })
		  return Promise.reject('登录已过期，请重新登录。')
		} else if (code === 500) {
		  uni.showToast({
			icon: 'none',
			title: msg
		  });
		  return Promise.reject(new Error(msg))
		} else if (code !== 200) {
		  return Promise.reject('error')
		} else {
		  return res.data
		}
	}
	function responseError(error) {
		console.log('err' + error)
		let { message } = error;
		if (message == "Network Error") {
		  message = "后端接口连接异常";
		}
		else if (message.includes("timeout")) {
		  message = "系统接口请求超时";
		}
		else if (message.includes("Request failed with status code")) {
		  message = "系统接口" + message.substr(message.length - 3) + "异常";
		}
		uni.showToast({
			icon: 'none',
			title: message
		});
		return error;
	}

module.exports = (config => {
	return new Promise((resolve, reject) => {
		const isToken = (config.headers || {}).isToken === false
		if (getToken() && !isToken) {
		  if(!config.headers) {
			  config.headers = {};
		  }	
		  config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
		}
		// get请求映射params参数
		if (config.method === 'get' && config.params) {
		  let url = config.url + '?' + tansParams(config.params);
		  url = url.slice(0, -1);
		  config.params = {};
		  config.url = url;
		}
		uni.request({
			header: config.headers,
			method: config.method,
			data: config.data,
			dataType: 'json',
			url: baseURL + config.url,
			success: res => {
				resolve(res.data);
			},
			fail: error => {
				reject(error);
			},
			complete(res) {
				resolve(responsePass(res));
			}
		});
	});
});